package com.acme.domain.bank;

import java.util.ArrayList;
import java.util.List;

public class Queue {

	private List<Email> queue;
	
	public Queue() {
		queue = new ArrayList<Email>();
	}
	
//	public void addEmail(Email email) {
//		queue.add(email);
//	}
//	
//	public synchronized void sendEmail() {
//		System.out.println(queue.get(0) + " removed");
//		queue.remove(0);
//	}
	
	public synchronized void addEmail(Email email) {
		queue.add(email);
		if(queue.size() == 1)
			notify();
	}
	
	
	// XXX: [VY] Ok, it works, but difficult to read and has some duplicates of code-lines
	// It can be optimized ;) Let's see my version sendEmailByVY()
	// more - is you use getSize() still use it ;)
	public synchronized void sendEmail() throws InterruptedException {
		if(getSize() > 1) {
			System.out.println(queue.get(0) + " removed");
			queue.remove(0);
		} else if(queue.size() == 1) {
			System.out.println(queue.get(0) + " removed");
			queue.remove(0);
			wait();
		} else {
			wait();
		}
	}

	// XXX: [VY] And even this code can be more elegant, 
	// please think about how it can be refactored. Thanks
	public synchronized void sendEmailByVY() throws InterruptedException {
		if(queue.size() >= 1) {
			System.out.println(queue.get(0) + " removed");
			queue.remove(0);
		}
		if (queue.isEmpty()){
			wait();
		}
	}

	
	// XXX: [VY] This method is redundant. Maybe... 
	public synchronized int getSize() {
		return queue.size();
	}
	
}
